const fs = require("fs");
const express = require("express");
const path = require('path');
const cors = require("cors");
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");
const axios = require('axios')

dayjs.extend(utc);
dayjs.extend(timezone);
const app = express();
app.use(express.json());
app.use(cors());

const dataFilePath = "./data.json";

let data = {
  USDT: [],
  PayPal: [],
  GooglePlay: [],
};

app.use(express.static(path.join(__dirname, 'public')));

function loadData() {
  if (fs.existsSync(dataFilePath)) {
    try {
      const rawData = fs.readFileSync(dataFilePath);
      data = JSON.parse(rawData);
    } catch (error) {
      console.error("Error reading data from file:", error);
    }
  } else {
    saveData();
  }
}

function saveData() {
  try {
    fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2));
  } catch (error) {
    console.error("Error writing data to file:", error);
  }
}

function generateSampleData(prefix, count, goldValues) {
  const goldArray = [];
  for (let i = 0; i < Math.floor(count * 0.7); i++)
    goldArray.push(goldValues[0]);
  for (let i = 0; i < Math.floor(count * 0.2); i++)
    goldArray.push(goldValues[1]);
  for (let i = 0; i < Math.floor(count * 0.1); i++)
    goldArray.push(goldValues[2]);

  return goldArray.map((gold, index) => {
    return {
      code: `${prefix}-${Math.random().toString(36).substr(2, 9)}`,
      type: prefix,
      gold: gold,
    };
  });
}

function initializeData() {
  if (!data.USDT.length && !data.PayPal.length && !data.GooglePlay.length) {
    data.USDT = generateSampleData("USDT", 1000, [50000, 100000, 200000]);
    data.PayPal = generateSampleData("PayPal", 1000, [50000, 100000, 200000]);
    data.GooglePlay = generateSampleData(
      "GooglePlay",
      1000,
      [50000, 100000, 200000]
    );
    saveData();
  }
}

loadData();
initializeData();

// 获取所有数据
app.get("/data", (req, res) => {
  res.json(data);
});

// 根据类型&兑换码获取数据
app.get("/data/:type", (req, res) => {
  const { type } = req.params;
  const { code, gold, name = "", userId = "" } = req.query;

  if (!data[type]) return res.status(404).json({ error: "Type not found" });
  let sendData = "";

  if (type && !!gold && !code) {
    sendData = data[type] || "not found";
    if (gold) {
      if (!data[type].filter((i) => +i.gold === +gold)?.length) {
        sendData = "The current redemption reward has been completed";
      } else {
        const itemIndex = data[type].findIndex(
          (i) => +i.gold === +gold && !i.UsedAlready
        );
        const ExchangeTime = dayjs()
          .tz('America/New_York')
          .format("YYYY-MM-DD HH:mm:ss");
        sendData = {
          ...data[type][itemIndex],
          length: data[type].filter((i) => +i.gold === +gold && !i.UsedAlready)
            ?.length - 1,
          ExchangeTime,
        };
        data[type][itemIndex].UsedAlready = true;
        data[type][itemIndex].ExchangeTime = ExchangeTime;
        data[type][itemIndex].name = name;
        data[type][itemIndex].userId = userId;
        saveData();
      }
    }
  } else if (!type && code) {
    sendData = allCode.find((i) => i.code === code) || "not found";
  }
  else if (type && code) {
    sendData = data[type]?.find((i) => i.code === code) || "not found";
  }
  else {
    sendData = data[type]
  }
  res.json(sendData);
});

// 添加数据
app.post("/data/:type", (req, res) => {
  const { type } = req.params;
  const { code, gold } = req.body;

  if (!data[type]) return res.status(404).json({ error: "Type not found" });

  const newItem = {
    code: code || `${type}-${Math.random().toString(36).substr(2, 9)}`,
    type,
    gold,
  };
  data[type].push(newItem);
  saveData();
  res.status(201).json(newItem);
});

// 删除数据
app.delete("/data/:type/:code", (req, res) => {
  const { type, code } = req.params;
  if (!data[type]) return res.status(404).json({ error: "Type not found" });

  const index = data[type].findIndex((item) => item.code === code);
  if (index === -1) return res.status(404).json({ error: "code not found" });

  const deletedItem = data[type].splice(index, 1);
  saveData();
  res.status(200).json(deletedItem);
});

// 兑换完成，更新数据
app.put("/data/:type", (req, res) => {
  const { type } = req.params;
  const { code } = req.body;
  if (!data[type]) return res.status(404).json({ error: "Type not found" });

  const item = data[type].find((item) => item.code === code && item.UsedAlready);
  if (!item) return res.status(404).json({ error: "Item not found" });

  item.redeemed = true;
  saveData();
  res.status(200).json(item);
});


// 转发获取平台广告接口
app.get('/adspaw_get', async (req, res) => {
  console.log('req.query', req.query)
  try {
    const response = await axios({
      method: 'GET',
      params: {
        ...req.query
      },
      url: 'https://api.adsgram.ai/adv',
      headers: {
        Origin: 'https://jardgames.com',
        Referer: 'https://jardgames.com/',
      },
    });
    res.json({
      ...response.data,
    });
  } catch (error) {
    res.status(error.response.status).json(error.response.data);
  }
});



// 转发平台广告回调事件
app.get('/adspaw_event', async (req, res) => {
  console.log('req.query', req.query)
  try {
    const response = await axios({
      method: 'GET',
      params: {
        ...req.query
      },
      url: 'https://api.adsgram.ai/event',
      headers: {
        Origin: 'https://jardgames.com',
        Referer: 'https://jardgames.com/',
      },
    });
    console.log('response', response.data)
    res.json({
      ...response.data,
    });
  } catch (error) {
    res.status(error.response.status).json(error.response.data);
  }
});

app.get('/get_baidu_driving_info', async (req, res) => {
  console.log('req.query', req.query)
  try {
    const response = await axios({
      method: 'GET',
      params: {
        ...req.query
      },
      url: 'https://api.map.baidu.com/directionlite/v1/driving',
    });
    console.log('response', response.data)
    res.json({
      ...response.data,
    });
  } catch (error) {
    res.status(error.response.status).json(error.response.data);
  }
});


const userCRUD = require("./user.js");
app.use("/user", userCRUD);


const inviteCRUD = require("./invite.js");
app.use("/invite", inviteCRUD);

const catch_error = require("./catch_error.js");
app.use("/catch_error", catch_error);


// 警务内务
const InternalAffairsManageCRUD = require("./xcx/InternalAffairsManage/index.js");
app.use("/internal_affairs_manage", InternalAffairsManageCRUD);

// 执勤备勤
const onDutyStandbyCRUD = require("./xcx/onDutyStandby/index.js");
app.use("/on_duty_standby", onDutyStandbyCRUD);

// 智能健康
const IntelligentHealth = require("./xcx/IntelligentHealth/index.js");
app.use("/intelligent_health", IntelligentHealth);

// 社区警务
const CommunityPolicing = require("./xcx/CommunityPolicing/index.js");
app.use("/community_policing", CommunityPolicing);

// 网络安全科普
const NetworkSecurityScience = require("./xcx/NetworkSecurity/index.js");
app.use("/network_security_science", NetworkSecurityScience);

// 人脸识别自习室
const FaceRecognition = require("./xcx/FaceRecognition/index.js");
app.use("/face_recognition", FaceRecognition);

// 道路状况
const RoadConditions = require("./xcx/RoadConditions/index.js");
app.use("/road_conditions", RoadConditions);

const Upload = require("./xcx/upload/index.js");
app.use("/upload", Upload);

// static
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 解决调用三方接口跨域
app.get('/topBuzz_new_list', async (req, res) => {
  try {
    const response = await axios({
      method: 'GET',
      params: {
        ...req.query
      },
      url: 'https://newsapi.org/v2/everything?q=Apple&from=2025-03-06&sortBy=popularity&apiKey=2a8213bad8204df2a0129b22909fb947',
      // headers: {
      //   Origin: 'https://www.toutiao.com',
      //   Referer: 'https://www.toutiao.com/',
      // },
    });
    // console.log('response',response)
    res.json(response.data);
  } catch (error) {
    console.log('error', error);

    // res.status(error.response.status).json(error.response.data);
  }
});

// 启动服务器
const PORT = 9901;
app.listen(PORT, () => {
  // console.log(`Server running on port ${PORT}`);
});

